package app.keter.portal.mail;

import app.keter.portal.config.Services;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.keter.framework.core.util.ConcurrentUtil;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 邮件发送器组件
 * Created by gulixing@msn.com on 2019/3/13.
 */
@Component
public class MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailService.class);

    @Autowired
    @Qualifier("mailTemplate") RestTemplate restTemplate;

    @Autowired
    Services services;

    private String MAIL_API;

    @Autowired void init() {
        MAIL_API = services.getCommon() +"/api/v1/mails";
    }

    /**
     * 同步发送邮件
     * @param mailObj
     */
    public JSONResult send(JSONObject mailObj){
        logger.info("发送邮件，to:{}, cc:{}, bcc:{}",mailObj.get("to"),mailObj.get("cc"),mailObj.get("bcc"));
        return restTemplate.postForObject(MAIL_API, mailObj, JSONResult.class);
    }

    // 声明线程池
    ListeningExecutorService service = ConcurrentUtil.service();
    /**
     * 异步发送邮件
     * @param mailObj
     */
    public  void sendAsync(JSONObject mailObj){
        //TODO: Sleuth模式下是否应使用它提供的线程池实现？
        service.submit(() -> {
            send(mailObj);
        });
    }
}
